package com.fattyCorps.utils;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fattyCorps.exception.gameException.TokenErrorException;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;

import javax.servlet.http.HttpServletRequest;

public class ServletUtils{

    public static Integer getAccIdByRequest(HttpServletRequest request){
        return getIdByRequest(request, JwtUtil.ACC_ID_NAME, true);
    }

    public static Integer getAccIdByRequest(HttpServletRequest request, boolean t){
        return getIdByRequest(request, JwtUtil.ACC_ID_NAME, t);
    }

    public static Integer getPlayerIdByRequest(HttpServletRequest request){
        return getIdByRequest(request, JwtUtil.PLAYER_ID_NAME, true);
    }

    public static Integer getPlayerIdByRequest(HttpServletRequest request, boolean t){
        return getIdByRequest(request, JwtUtil.PLAYER_ID_NAME, t);
    }

    private static Integer getIdByRequest(HttpServletRequest request, String idName, boolean t){
        String token = request.getHeader("token");
        if (token==null){
            if (!t) {
                return 0;
            }

            throw new TokenErrorException();
        }
        DecodedJWT decodedJWT;
        try {
            decodedJWT = JwtUtil.verify(token);
        } catch (Exception e){
            throw new TokenErrorException();
        }

        Integer id = decodedJWT.getClaim(idName).asInt();
        if (id==null){
            if (!t) {
                return 0;
            }

            throw new TokenErrorException();
        }
        return id;
    }
}